package org.freedoit.client;

import org.freedoit.shared.exception.ServerException;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.event.dom.client.ClickEvent;

public class LoginWidget extends Composite {

	private static LoginWidgetUiBinder uiBinder = GWT
			.create(LoginWidgetUiBinder.class);

	@UiField Label lblPassword;
	@UiField PasswordTextBox pwPassword;
	@UiField Button btnLogin;
	@UiField Button btnCancel;
	@UiField Label lblUserName;
	@UiField TextBox tbUserName;
	@UiField Label lblError;

	interface LoginWidgetUiBinder extends UiBinder<Widget, LoginWidget> {
	}

	private final LoginServiceAsync loginService = GWT
			.create(LoginService.class);

	public LoginWidget() {
		initWidget(uiBinder.createAndBindUi(this));
	}

	public LoginWidget(String firstName) {
		initWidget(uiBinder.createAndBindUi(this));
	}

	@UiHandler("btnLogin")
	void onBtnLoginClick(ClickEvent event) {

		lblError.setText(""); // clear error message if exists

		// Check user name
		String username = tbUserName.getText();
		if (username == null || username.length() == 0)
		{
			lblError.setText("User Name Required");
			return;
		}
		
		String password = pwPassword.getText();
		if (password == null || password.length() == 0)
		{
			lblError.setText("Password Required");
			return;
		}

		loginService.login(username, password, new AsyncCallback<String>() {

			public void onFailure(Throwable caught) {
				// TODO Auto-generated method stub
				if (caught instanceof ServerException) {
					lblError.setText("Internal Server Error");
				} else {
					lblError.setText(caught.getMessage());
				}
			}

			public void onSuccess(String result) {
				// TODO Auto-generated method stub
				lblError.setText(result);
			}
			
		});
	}
	@UiHandler("btnCancel")
	void onBtnCancelClick(ClickEvent event) {
	}
}
